﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.SqlClient;
using System.Data;

namespace weikebuluo.DBUtility
{
    /// <summary>
    /// 数据访问抽象基础类
    /// Copyright (C) weikebuluo
    /// </summary>
    public abstract class DbHelperDynamicSQL
    {
        //数据库连接字符串(web.config来配置)，多数据库可使用DbHelperSQLP来实现.
        public static string connectionString = PubConstant.ConnectionString;

        public DbHelperDynamicSQL()
        { }

        #region 生成SqlParameter参数
        /// <summary>
        /// 生成SqlParameter参数
        /// </summary>
        /// <param name="paramStr">多个参数组成的串</param>
        /// <param name="addReturnParam">是否增加返回参数</param>
        /// <param name="values">字段的值一维array</param>
        /// <returns>
        /// SqlParameter[]
        /// </returns>
        public static SqlParameter[] GetSqlParams(string paramStr, bool addReturnParam, params object[] values)
        {
            SqlParameter[] arParams = null;

            if ((paramStr != null) && (paramStr.Trim() != ""))
            {
                string[] paramStrs = paramStr.Split(new Char[] { ',' });

                arParams = new SqlParameter[paramStrs.Length];

                int i = 0;

                foreach (string param in paramStrs)
                {
                    if (values[i] == null)

                        arParams[i] = new SqlParameter(param.Trim(), DBNull.Value);

                    else

                        arParams[i] = new SqlParameter(param.Trim(), values[i]);

                    i++;
                }
            }

            if (addReturnParam)
            {
                AddReturnParam(ref arParams, "@ReturnValue", SqlDbType.Int);
            }

            return arParams;
        }
        #endregion 生成SqlParameter参数

        #region AddReturnParam函数
        /// <summary>
        /// AddReturnParam函数
        /// </summary>
        /// <param name="arParams">SqlParameter</param>
        /// <param name="paramName">参数名</param>
        /// <param name="ot">类型</param>
        public static void AddReturnParam(ref SqlParameter[] arParams, string paramName, SqlDbType ot)
        {
            SqlParameter newParam = new SqlParameter(paramName.Trim(), ot, 2000);

            newParam.Direction = ParameterDirection.ReturnValue;

            if (arParams == null)
            {
                arParams = new SqlParameter[] { newParam };

                return;
            }

            SqlParameter[] newParams = new SqlParameter[arParams.Length + 1];

            for (int i = 0; i < arParams.Length; i++)
            {
                newParams[i] = arParams[i];
            }

            newParams[arParams.Length] = newParam;

            arParams = newParams;
        }
        #endregion AddReturnParam函数
    }
}
